package com.zhouyibike.uu.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteLine;
import com.baidu.mapapi.search.route.WalkingRoutePlanOption;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.google.gson.Gson;
import com.tencent.mm.opensdk.constants.Build;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.zhouyibike.uu.R;
import com.zhouyibike.uu.entity.MyReceiverResult;
import com.zhouyibike.uu.entity.OrderUnPayNewResult;
import com.zhouyibike.uu.entity.PayResult;
import com.zhouyibike.uu.entity.WXBikeBuyResult;
import com.zhouyibike.uu.ui.activity.mywallet.MyYHQActivity;
import com.zhouyibike.uu.ui.activity.redwallet.OpenrwActivity;
import com.zhouyibike.uu.ui.base.BaseActivity;

import java.text.DecimalFormat;
import java.util.Map;

import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;

public class RaidingEndActivity extends BaseActivity implements View.OnClickListener,CompoundButton.OnCheckedChangeListener,OnGetRoutePlanResultListener {
    private ImageButton mBtnBack;
    private TextView mBtnTitle;
    private String orderId;
    private OrderUnPayNewResult.DataBean msg;
    private MyReceiverResult tsmsg;
    private TextView tv_mails,tv_times,tv_totalmoney,tv_ycq,tv_yue,tv_yingfu,tv_bikenum;
    private Button btn_pay;
    private CheckBox cb_zfb,cb_wx;
    private TextView tv_selectpaytype;
    private LinearLayout ll_paytype;
    private String paytype="0";
    private IWXAPI api;
    private boolean ists;//是否推送过来的
    private LinearLayout ll_ycq;
    private boolean isneedpay;
    private RoutePlanSearch mSearch = null;    // 搜索模块，也可去掉地图模块独立使用
    DecimalFormat df = new DecimalFormat("######0.00");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_raiding_end);
        mSearch = RoutePlanSearch.newInstance();
        mSearch.setOnGetRoutePlanResultListener(this);
        ists=getIntent().getBooleanExtra("ists",false);
        isneedpay=getIntent().getBooleanExtra("needpay",true);
        api = WXAPIFactory.createWXAPI(this, null);
        EventBus.getDefault().register(this);
        initView();
        if(ists){
            tsmsg= (MyReceiverResult) getIntent().getSerializableExtra("msg");
            orderId=tsmsg.getOrderId();
            initmsgts();
        }else {
            msg = (OrderUnPayNewResult.DataBean) getIntent().getSerializableExtra("msg");
            orderId=msg.getOrderId();
            initmsg();
        }
        try {
            if (tsmsg.isRedBag()&&!tsmsg.getRedBag().equals("0"))
    //            if (tsmsg.isRedBag())
            {
                Intent intent=new Intent(this, OpenrwActivity.class);
                intent.putExtra("hongbaovalue",tsmsg.getRedBag());
                intent.putExtra("maxhongbao",tsmsg.getMaxRedBag());
                startActivity(intent);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void initView() {
        mBtnBack = (ImageButton) findViewById(R.id.bar_btn_back);
        mBtnTitle = (TextView) findViewById(R.id.bar_text_title);
        mBtnTitle.setText("结束行程");
        mBtnBack.setOnClickListener(this);
        mBtnBack.setVisibility(View.GONE);
        RelativeLayout barly;
        barly = (RelativeLayout) findViewById(R.id.barly);
        barly.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });
        barly.setVisibility(View.INVISIBLE);
        tv_bikenum= (TextView) findViewById(R.id.tv_radingend_bikenum);
        tv_mails= (TextView) findViewById(R.id.tv_raidingend_mails);
        tv_times= (TextView) findViewById(R.id.tv_raidingend_times);
        tv_totalmoney= (TextView) findViewById(R.id.tv_radingend_totalmoney);
        tv_ycq= (TextView) findViewById(R.id.tv_radingend_ycq);
        tv_yue= (TextView) findViewById(R.id.tv_radingend_yue);
        tv_yingfu= (TextView) findViewById(R.id.tv_radingend_yingfu);
        cb_wx= (CheckBox) findViewById(R.id.cb_radingend_wx);
        cb_zfb= (CheckBox) findViewById(R.id.cb_radingend_zfb);
        cb_wx.setOnCheckedChangeListener(this);
        cb_zfb.setOnCheckedChangeListener(this);
        btn_pay= (Button) findViewById(R.id.btn_radingend_pay);
        btn_pay.setOnClickListener(this);
        if(!isneedpay){
            btn_pay.setText("确定");
        }

        tv_selectpaytype= (TextView) findViewById(R.id.tv_rading_selectpaytype);
        ll_paytype= (LinearLayout) findViewById(R.id.ll_rading_paytype);
        ll_ycq= (LinearLayout) findViewById(R.id.ll_radingend_ycq);
        ll_ycq.setOnClickListener(this);
    }

    @Override
    public void onBackPressed() {

    }
    private void getdis(){
        PlanNode stNode = PlanNode.withLocation(new LatLng(msg.getStartLatitude(),msg.getStartLongitude()));
        PlanNode enNode = PlanNode.withLocation(new LatLng(msg.getEndLatitude(),msg.getEndLongitude()));
        mSearch.walkingSearch(new WalkingRoutePlanOption().from(stNode).to(enNode));
    }
    private void getdists(){
        PlanNode stNode = PlanNode.withLocation(new LatLng(Double.parseDouble(tsmsg.getStartLatitude()),Double.parseDouble(tsmsg.getStartLongitude())));
        PlanNode enNode = PlanNode.withLocation(new LatLng(Double.parseDouble(tsmsg.getEndLatitude()),Double.parseDouble(tsmsg.getEndLongitude())));
        mSearch.walkingSearch(new WalkingRoutePlanOption().from(stNode).to(enNode));
    }
    private void initmsg(){
        tv_bikenum.setText(msg.getPlateNumber());
        tv_mails.setText(msg.getMileage()+"");
        tv_times.setText(msg.getMinutes()+"");
        tv_totalmoney.setText(msg.getTotalAmount()+"");
        tv_ycq.setText(msg.getPackageAmount()+"");
        tv_yue.setText(msg.getWalletAmount()+"");
        tv_yingfu.setText(df.format(msg.getTotalAmount()-msg.getPackageAmount()-msg.getWalletAmount()));
        if(msg.isNeedPay()){
            tv_selectpaytype.setVisibility(View.VISIBLE);
            ll_paytype.setVisibility(View.VISIBLE);
            paytype="1";
        }
        getdis();
    }
    private void initmsgts(){
        tv_bikenum.setText(tsmsg.getPlateNumber());
        tv_mails.setText(tsmsg.getMileage()+"");
        tv_times.setText(tsmsg.getMinutes()+"");
        tv_totalmoney.setText(tsmsg.getTotalAmount()+"");
        tv_ycq.setText(tsmsg.getPackageAmount()+"");
        tv_yue.setText(tsmsg.getWalletAmount()+"");
        tv_yingfu.setText(df.format(tsmsg.getTotalAmount()-tsmsg.getPackageAmount()-tsmsg.getWalletAmount()));
        if(tsmsg.isNeedPay()){
            tv_selectpaytype.setVisibility(View.VISIBLE);
            ll_paytype.setVisibility(View.VISIBLE);
            paytype="1";
        }
        getdists();
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bar_btn_back:
                finish();
                break;
            case R.id.btn_radingend_pay:
                if(!isneedpay){
                    setResult(1);
                    finish();
                }else{
                    if(ists){
                        endradingts();
                    }else{
                        endrading();

                    }
                }
                break;
            case R.id.ll_radingend_ycq:
                startActivity(new Intent(this, MyYHQActivity.class));
                break;
        }
    }
    private void endrading(){

                            if(paytype.equals("2")){
                                zfbpay(msg.getAlipay());
                            }else{
                                wxpay(msg.getWeChat());
                            }

    }
    private void endradingts(){

        if(paytype.equals("2")){
            zfbpay(tsmsg.getAlipay());
        }else{
            wxpay(tsmsg.getWeChat());
        }

    }
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        switch (buttonView.getId()){
            case R.id.cb_radingend_wx:
                if(isChecked){
                    cb_zfb.setChecked(false);
                    paytype="1";
                }else{
                    cb_zfb.setChecked(true);
                    paytype="2";
                }
                break;
            case R.id.cb_radingend_zfb:
                if(isChecked){
                    cb_wx.setChecked(false);
                    paytype="2";
                }else{
                    cb_wx.setChecked(true);
                    paytype="1";
                }
                break;
        }
    }
    private void wxpay(String modelmsg){
        WXBikeBuyResult model=new Gson().fromJson(modelmsg,WXBikeBuyResult.class);
        api.registerApp( model.getAppId());
        boolean isPaySupported = api.getWXAppSupportAPI() >= Build.PAY_SUPPORTED_SDK_INT;
        if(!isPaySupported){
            Toast.makeText(RaidingEndActivity.this, "您的微信版本太低，不支持支付功能", Toast.LENGTH_SHORT).show();
            return;
        }
        Toast.makeText(RaidingEndActivity.this, "获取订单中...", Toast.LENGTH_SHORT).show();
        try{
            PayReq request = new PayReq();

            request.appId = model.getAppId();

            request.partnerId = model.getPartnerId();

            request.prepayId= model.getPrepayId();

            request.packageValue ="Sign=WXPay";

            request.nonceStr= model.getNoncestr();

            request.timeStamp=model.getTimestamp();

            request.sign= model.getSign();

            api.sendReq(request);

        }catch(Exception e){
            Toast.makeText(RaidingEndActivity.this, "异常："+e.getMessage(), Toast.LENGTH_SHORT).show();
        }

    }
    @Subscribe(threadMode = ThreadMode.MainThread)
    public void wxpayresult(Integer progress) {
        if(progress==0){//支付成功
            paysuccess();
        }else{
            Toast.makeText(RaidingEndActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
        }
    }
    private void zfbpay(final String orderinfo){

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(RaidingEndActivity.this);
                Map<String, String> result = alipay.payV2(orderinfo, true);
                Log.i("msp", result.toString());

                Message msg = new Message();
                msg.what = 1;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (resultStatus.equals("9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        paysuccess();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        Toast.makeText(RaidingEndActivity.this, "支付失败", Toast.LENGTH_SHORT).show();
                    }
                    break;
                }

                default:
                    break;
            }
        }
    };
    private void paysuccess(){
        setResult(1);
        finish();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onGetWalkingRouteResult(WalkingRouteResult walkingRouteResult) {
        if (walkingRouteResult.error == SearchResult.ERRORNO.NO_ERROR) {
            WalkingRouteLine walkingRouteLine=walkingRouteResult.getRouteLines().get(0);
            if (tv_mails.getText().toString().equals("0"))
            {
                  tv_mails.setText(walkingRouteLine.getDistance()/1000+"."+walkingRouteLine.getDistance()%1000);
            }

        }
    }

    @Override
    public void onGetTransitRouteResult(TransitRouteResult transitRouteResult) {

    }

    @Override
    public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

    }

    @Override
    public void onGetDrivingRouteResult(DrivingRouteResult drivingRouteResult) {

    }

    @Override
    public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

    }

    @Override
    public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

    }
}
